package controller.ur;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.ProfileImageDaoLocal;
import model.dao.UserDaoLocal;
import model.entity.ProfileImage;
import model.entity.User;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import controller.CUtil;

/**
 * Servlet implementation class SChangeProfilePictureOut
 */
public class SChangeProfilePictureOut extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	private Logger log = Logger.getLogger(SChangeProfilePictureOut.class);
	
	@EJB
	private UserDaoLocal userDao;
	
	@EJB
	private ProfileImageDaoLocal profileDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SChangeProfilePictureOut() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		request.setCharacterEncoding("UTF-8");
		
		User user=(User)request.getSession().getAttribute("user");
		if (ServletFileUpload.isMultipartContent(request)) {
			List<FileItem> items = null;
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(3000000);
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setSizeMax(3000000);
				items =upload.parseRequest(request);
				
				for (FileItem f : items) {
					if (!f.isFormField()) {
						ProfileImage profileImage=null;
						String imageFilePath=null;
						log.info(profileImage);
						if(user.getProfileImage()==null){
							profileImage=new ProfileImage();
							log.info(profileImage);
							profileDao.persist(profileImage);
							String extension = (f.getName().split("\\."))[1];
							imageFilePath = "\\images\\profil" + profileImage.getId() + "."
									+ extension;
						}else{
							profileImage=user.getProfileImage();
							imageFilePath=profileImage.getLocation();
							File file=new File(getServletContext().getRealPath("")+imageFilePath);
							file.delete();
						}
						File uploadedFile = new File(getServletContext().getRealPath("")+imageFilePath);
						try {
							f.write(uploadedFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
						BufferedImage img = null;
						try {
						    img = ImageIO.read(new File(getServletContext().getRealPath("")+imageFilePath));
						} catch (IOException e) {
						}
						
						log.info(profileImage);
						profileImage.setHeight(img.getHeight());
						profileImage.setWidth(img.getWidth());
						profileImage.setLocation(imageFilePath);
						profileImage.setSize((int)f.getSize());
						profileImage.setUploadDate(new Date());
						profileDao.merge(profileImage);
						user.setProfileImage(profileImage);
						userDao.merge(user);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			CUtil.lastPageRedirect(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
